# -*- coding: utf-8 -*-


from multiprocessing import Process
import time,json
import paho.mqtt.client as mqtt

host="39.96.40.177"
# host="127.0.0.1"
def on_message_sub(client, userdata, msg):
    res=str(msg.payload,encoding="utf-8")
    print("recieived"+msg.topic + " sub " + res)
    if res=="wq9":
        pub_msg("receive topic","100")

def sub_msg(topic):
    client = mqtt.Client()
    client.username_pw_set("wq", password="a")
    client.on_message = on_message_sub
    client.connect(host, 1883, 600)
    client.subscribe(topic, qos=0)
    client.loop_forever()

def pub_msg(topic,msg):
    client = mqtt.Client()
    client.username_pw_set("wq", password="a")
    client.will_set(topic, 'Last will message', 0, False)
    client.connect(host, 1883, 600)
    client.publish(topic, payload=msg, qos=0)
    # 主动断开没有遗言
    client.disconnect()

def main():
    dic={"topic":"wq","data":"&poiupo&&&&&"}
    sub1=Process(target=sub_msg,args=("wq",))
    sub1.start()
    for i in range(10):
        pub=Process(target=pub_msg,args=("wq",json.dumps(dic)))
        print(i)
        pub.start()

if __name__ == '__main__':
    main()



